package cn.tony.game.super_tank.msg;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import cn.tony.game.super_tank.Game;

public class JoinMessage extends Message {

    private int   type = 1;

    public String name;

    public int    id;

    public int    x;

    public int    y;

    public int    dir;

    public int    currentBlood;

    @Override
    public void send(Socket socket) {
        // dos
        try {
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

            dos.writeInt(type);

            dos.writeUTF(name);
            dos.writeInt(id);
            dos.writeInt(x);
            dos.writeInt(y);
            dos.writeInt(dir);
            dos.writeInt(currentBlood);
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void reslove(DataInputStream dis) {
        try {
            name = dis.readUTF();
            id = dis.readInt();
            x = dis.readInt();
            y = dis.readInt();
            dir = dis.readInt();
            currentBlood = dis.readInt();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(this);
    }

    public void doSomething(Game game) {
        System.out.println("doSomething game.id : " + game.id);
        System.out.println(this);

        if (game.id == id) {
            game.addself(id, name, x, y, dir, currentBlood);
        } else {
            
            if (!game.extis(id)) {
                System.out.println("插入id:"+id);

                game.addTank(id, name, x, y, dir, currentBlood);
                JoinMessage join = buildMsg(game);
                try {
                    join.send(game.socket);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } 

        }
    }

    public JoinMessage buildMsg(Game game) {
        JoinMessage join = new JoinMessage();
        join.dir = game.player.dir == 0 ? game.player.oDir : game.player.dir;
        join.x = game.player.x;
        join.y = game.player.y;
        join.id = game.player.id;
        join.currentBlood = game.player.gettBloodStrip();
        join.name = game.player.name.name;
        return join;
    }

    @Override
    public String toString() {
        return "JoinMessage [type=" + type + ", name=" + name + ", id=" + id + ", x=" + x + ", y=" + y + ", dir=" + dir + "]";
    }

}
